package com.hhkj.study.common.controller;

import com.github.pagehelper.PageInfo;
import com.hhkj.study.common.service.WeComService;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author luowu
 * @Date 2024/9/14 涵 10:15:21
 */
@RestController
@RequestMapping("/wecom")
public class WeComController {

    @Resource
    private WeComService wecomService;


    /**
     * 获得标签下用户列表
     * @param tagId
     * @return
     */
    @GetMapping(value = {"/user/list", "/user/list/{tagId}"})
    public TableDataInfo weComUserList(@PathVariable(required = false) Integer tagId) {
        return getDataTable(wecomService.weComUserList(tagId));
    }
    /**
     * 回调方法前必须验证url
     * @param msgSignature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @param corpId
     * @param agentId
     * @return
     */
    @GetMapping("/callback/{corpId}/{agentId}")
    public String verifyUrl(@RequestParam("msg_signature") String msgSignature,
                            @RequestParam String timestamp,
                            @RequestParam String nonce,
                            @RequestParam String echostr,
                            @PathVariable String corpId,
                            @PathVariable String agentId) {
        return wecomService.verifyUrl(agentId, corpId, msgSignature, timestamp, nonce, echostr);
    }

    /**
     * 消费回调数据
     *
     * @param msgSignature 签名  能保证唯一
     * @param timestamp    时间戳
     * @param nonce        nonce串 防止重放攻击
     * @param xmlBody      XML格式的响应体需要解密处理
     * @param corpId       企业ID
     * @param agentId      应用ID
     * @return the string
     */
    @PostMapping("/callback/{corpId}/{agentId}")
    public String consume(@RequestParam("msg_signature") String msgSignature,
                          @RequestParam String timestamp,
                          @RequestParam String nonce,
                          @RequestBody String xmlBody,
                          @PathVariable String corpId,
                          @PathVariable String agentId) {
        return wecomService.consumeCallback(agentId, corpId, msgSignature, timestamp, nonce, xmlBody);
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }
}
